<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2020/6/5
 * Time: 18:16
 */

namespace App\Logic;

use App\HttpController\Group;
use App\Model\UserModel;
use App\Services\ChatService;
use App\Services\GroupService;
use App\Services\HelpService;
use App\Services\PrivateMsgService;
use App\Services\ReponseCodeService;
use EasySwoole\EasySwoole\Config;
use App\Model\GroupModel;
use App\Model\UserGroupModel;
use EasySwoole\ORM\DbManager;
use EasySwoole\EasySwoole\Logger;
use vierbergenlars\SemVer\expression;

class GroupLogic
{
    /**
     * 获取全部群的哈希
     */
    public function groupHash($userId){
        try{
            $where = array();
            $where['user_groups.user_id'] = $userId;
            $where['user_groups.status'] = UserGroupModel::STATUS_NORMAL;
            $where['group_lists.status'] = GroupModel::STATUS_NORMAL;
            $groupList = UserGroupModel::create()
                ->join('group_lists','user_groups.group_id=group_lists.id')
                ->order('group_lists.id','asc')->field('group_lists.id,group_lists.version')->all($where);
            echo json_encode(  $groupList).PHP_EOL;
            if(empty($groupList)){
                return '';
            }
            $str = '';
            foreach ($groupList as $group){
                if(empty($group)){
                    continue;
                }
                $str = $str.$group['id'].$group['version'];
            }
            echo '字符串带签名'.$str.PHP_EOL;
            return md5($str);
        }catch(\Throwable $t){
            echo $t->getMessage();
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        }
    }

    /**
     * 群是否存在
     */
    public function groupExit($groupId){
        try{
            $where['id'] = $groupId;
            $where['status'] = GroupModel::STATUS_NORMAL;
            $group = GroupModel::create()->where($where)->column('id');
            if(empty($group)){
                return true;
            }
            return false;
        }catch(\Throwable $t){
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        }
    }

    /**修改群主
     * @param $groupId群id
     * @param $newOwnerUserId新的群主用户id
     */
    public function changgeGroupOwner($groupId,$ownerUserId,$newOwnerUserId){
        try{
            //开启事务
            DbManager::getInstance()->startTransaction();
            #修改群主
            GroupModel::create()->update(['user_id'=>$newOwnerUserId,'version'=>HelpService::createVersion(),'updated_at'=>HelpService::msectimeToStr(HelpService::msectime())],['id'=>$groupId]);
            #修改原群主角色
            UserGroupModel::create()->update(['role'=>UserGroupModel::ROLE_TYPE_MEMBER,'version'=>HelpService::createVersion(),'updated_at'=>HelpService::msectimeToStr(HelpService::msectime())],['group_id'=>$groupId,'user_id'=>$ownerUserId]);
            #修改新的群主角色
            UserGroupModel::create()->update(['role'=>UserGroupModel::ROLE_TYPE_MEMBER,'version'=>HelpService::createVersion(),'updated_at'=>HelpService::msectimeToStr(HelpService::msectime())],['group_id'=>$groupId,'user_id'=>$newOwnerUserId]);
        } catch(\Throwable  $e){
            //回滚事务
            DbManager::getInstance()->rollback();
            return ReponseCodeService::CODE_FAILE;
        } finally {
            //提交事务
            DbManager::getInstance()->commit();
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        }
    }

    /**获取客服群
     * @param $param
     */
    public function getServiceGroup($userId,$appUserId,$appId){
        try{
            $group = GroupModel::create()
                ->get(['app_user_id'=>$appUserId,'app_id'=>$appId,'service_user_id'=>[0,'>']]);
            #自动创建客服群
            if(empty($group)){
                #自动分配客服，客服在线信息，后续处理，目前直接随机
                $service_user_id = 1;
                $groupData['user_id'] = $userId;
                $groupData['app_id'] = $appId;
                $groupData['service_user_id'] = $service_user_id;
                $groupData['version']=HelpService::createVersion();
                $groupData['app_user_id'] = $appUserId;
                $groupData['created_at'] = HelpService::msectimeToStr(HelpService::msectime());
                $groupData['updated_at'] = HelpService::msectimeToStr(HelpService::msectime());
                GroupModel::create()->data($groupData)->save();
                $group = GroupModel::create()->get(['app_user_id'=>$appUserId,'app_id'=>$appId,'service_user_id'=>1]);
                #把用户啦到群里
                $userGroupData['app_id'] =  $appId;
                $userGroupData['app_user_id'] = $appUserId;
                $userGroupData['user_id'] =  $userId;
                $userGroupData['role'] =  UserGroupModel::ROLE_TYPE_CREATER;
                $userGroupData['version'] = HelpService::createVersion();
                $userGroupData['group_id'] =  $group['id'];
                $userGroupData['status'] = UserGroupModel::STATUS_NORMAL;
                $userGroupData['created_at'] = HelpService::msectimeToStr(HelpService::msectime());
                $userGroupData['updated_at'] = HelpService::msectimeToStr(HelpService::msectime());
                UserGroupModel::create()->data($userGroupData)->save();
            }

            return  $group;
        }catch(\Throwable $t){

            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        }
    }

    /**
     * 群详情
     */
    public function groupDetail($groupId,$userId,$page,$limit,$updatedAt=''){

    }

    /**
     * 获取群成员列表
     */
    public function groupMemberList($appId,$groupId,$page,$limit,$updatedAt='',$where=array()){
        try{
            $model = UserGroupModel::create()
                ->join('users','user_groups.app_user_id=users.app_user_id','left')
                ->field('user_groups.app_user_id,user_groups.version,user_groups.nickname_in_group,user_groups.status,user_groups.created_at,user_groups.updated_at,user_groups.role,users.app_user_id,users.nickname,users.head')
                ->limit($limit * ($page - 1), $limit)->withTotalCount()
                ->order('user_groups.updated_at');
            $groupMemberListCondition['user_groups.app_id'] = $appId;
            $groupMemberListCondition['users.app_id'] = $appId;
            $groupMemberListCondition['user_groups.group_id'] = $groupId;
            if(!empty($updatedAt)){
                $groupMemberListCondition['user_groups.updated_at'] = [HelpService::msectimeToStr($updatedAt),'>='];
            }else{#不带时间只给群状态正常，没有退群的信息给客户端
                $groupMemberListCondition['user_groups.status'] = UserGroupModel::STATUS_NORMAL;
            }

            if(!empty($where)){
                $groupMemberListCondition = array_merge($groupMemberListCondition,$where);
            }
            $list = $model->all($groupMemberListCondition);
            $result = $model->lastQueryResult();
            $total = $result->getTotalCount();
            $totalPage = ceil($total/$limit);
            if(!empty($list)){
                foreach ($list as &$val){
                    $val['created_at'] = HelpService::strDateToMsectime($val['created_at']);
                    $val['updated_at'] = HelpService::strDateToMsectime($val['updated_at']);
                }
            }

            $data['limit']  = $limit;
            $data['page']  = $page;
            $data['list'] = $list;
            $data['total'] = $totalPage;
            $data['total_page']  = $totalPage;
            return $data;
         }catch(\Throwable $t){
            echo $t->getMessage().'邀请错误';
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        }
    }


    /**创建群
     * @param $userId创建人用户id
     * @param $groupName群名
     * @param $userIdArr群成员id
     * @param  $serviceUserId 客服用户id
     * @param  $cover 群封面图
     */
    function createGroup($userId,$appUserIdArr,$appId,$groupName='',$cover='',$serviceUserId=''){
        try{
            $userInfo = UserModel::create()->get(['id'=>$userId]);
            //开启事务
            DbManager::getInstance()->startTransaction();
            $groupData = [
                'user_id' => $userId,
                'app_id' => $userInfo['app_id'],
                'app_user_id'=>$userInfo['app_user_id'],
                'service_user_id'=>$serviceUserId,
                'version'=>HelpService::createVersion(),
                'member_count'=>(count($appUserIdArr)+1),
                'created_at'  => HelpService::msectimeToStr(HelpService::msectime()),
                'updated_at'  => HelpService::msectimeToStr(HelpService::msectime()),
            ];
            if(!empty($cover)){
                $groupData['cover'] = $cover;
            }

            //创建群
            $groupId =  GroupModel::create()->data($groupData, false)->save();
            #本身入群
            UserGroupModel::create()->data([
                'user_id'=>$userId,
                'app_id'=>$appId,
                'group_id'=>$groupId,
                'app_user_id'=>"{$userInfo['app_user_id']}",
                'role'=>UserGroupModel::ROLE_TYPE_CREATER,
                'version'=>HelpService::createVersion(),
                'created_at'  => HelpService::msectimeToStr(HelpService::msectime()),
                'updated_at'  => HelpService::msectimeToStr(HelpService::msectime()),
            ])->save();
            $tempName = '';
            #成员加入群聊
            $userLogic = new UserLogic();
            foreach($appUserIdArr as $appUserId){
                if(!$userLogic->userExit(['app_id'=>$appId,'app_user_id'=>$appUserId])){
                    echo '用户不存在';
                    continue;
                }
                echo '用户存在';
                $userInfo = $userLogic->findByAppUserIdByAppId($appId,$appUserId);
                UserGroupModel::create()->data([
                    'user_id'=> $userInfo['id'],
                    'app_id'=>$appId,
                    'app_user_id'=>$userInfo['app_user_id'],
                    'group_id'=>$groupId,
                    'version'=>HelpService::createVersion(),
                    'role'=>UserGroupModel::ROLE_TYPE_MEMBER,
                    'created_at'  => HelpService::msectimeToStr(HelpService::msectime()),
                    'updated_at'  => HelpService::msectimeToStr(HelpService::msectime()),
                ])->save();
                $tempName =  $tempName.'、'.$userInfo['nickname'];
            }
            #更新群名字
            if(empty($groupName)){
                $groupService = new GroupService();
                $tempName = $groupService->createTempName($tempName);
                $groupName = $tempName;
            }
            #
            echo '更新群标题'.$groupName.PHP_EOL;
            GroupModel::create()->get($groupId)->update(["group_name"=>$groupName]);
        } catch(\Throwable  $e){
            echo $e->getMessage();
            //回滚事务
            DbManager::getInstance()->rollback();
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        } finally {
            //提交事务
            DbManager::getInstance()->commit();
        }
        #返回群信息
        return $groupId;
    }

    /**邀请用户入群
     * @param $groupId
     * @param $userIdArr
     */
   function invite($appId,$groupId,$appUserIdArr){
       try{
           $groupInfo = GroupModel::create()->get(['id'=>$groupId]);
           if(empty($groupInfo)){
               return ReponseCodeService::CODE_FAILE;
           }

            $ret = array();
            $sucessArr = array();
            foreach($appUserIdArr as $appUserId){
                echo '邀请'.$appUserId.PHP_EOL;
                if(empty($appUserId)){
                    continue;
                }
                #是否注册过
                $userInfo = UserModel::create()->get(['app_user_id'=>$appUserId,'app_id'=>$appId]);
                $joinRet['app_user_id'] = $appUserId;
                if(empty($userInfo)){
                    $joinRet['ret'] = false;
                    $joinRet['msg'] = '用户不存在';
                    $ret[] = $joinRet;
                    continue;
                }

                #是否在群里
                if(UserGroupModel::create()->get(['app_user_id'=>$appUserId,'app_id'=>$appId,'group_id'=>$groupId,'status'=>UserGroupModel::STATUS_NORMAL])){
                    $joinRet['ret'] = false;
                    $joinRet['msg'] = '已经在群里';
                    $ret[] = $joinRet;
                    continue;
                }

                #添加入群
                $joinInfo['app_id'] = $appId;
                $joinInfo['app_user_id'] = $appUserId;
                $joinInfo['user_id'] =  $userInfo['id'];
                $joinInfo['group_id'] = $groupId;
                $joinInfo['role'] = UserGroupModel::ROLE_TYPE_MEMBER;
                $joinInfo['status'] = UserGroupModel::STATUS_NORMAL;
                $joinInfo['version']=HelpService::createVersion();
                $joinInfo['created_at'] = HelpService::msectimeToStr(HelpService::msectime());
                $joinInfo['updated_at'] = HelpService::msectimeToStr(HelpService::msectime());
                if( UserGroupModel::create()->data( $joinInfo)->save()){
                    $joinRet['ret'] =true;
                    $joinRet['msg'] = '加入成功';
                    $joinRet['app_user_id'] = $appUserId;
                   $ret[] = $joinRet;
                    $sucessArr[] = $appUserId;
                }
                unset($joinInfo);
                unset($appUserId);
            }

       } catch(\Throwable $t){
           echo $t->getMessage();
           return  ['ret'=>$ret,'sucessArr'=>$sucessArr,'code'=>ReponseCodeService::CODE_SERVICE_UNAVAILABLE];
       }

       return  ['ret'=>$ret,'sucessArr'=>$sucessArr,'code'=>ReponseCodeService::CODE_OK];
   }
}